
/**                            
* 方法:Array.Contains(obj)     
* 功能:确定某个元素是否在数组中.        
* 参数:要查找的Object对象 
* 返回:找到返回true,否则返回false; 
*/                                                
Array.prototype.contains=function(obj) 
{ 
   for(var i=0;i<this.length;i++) 
   { 
    if(this[i]==obj)
    { 
     return true; 
    } 
   } 
   return false; 
} 



function StringBuffer() {
	this._strings_ = new Array();
	this.append = function(str) {
		this._strings_.push(str);
	}
	this.toString = function() {
		return this._strings_.join('');
	}
}

/**
 * 系统参考变量
 * 
 * @type
 */
var ccms={
	areas:['全部','东区', '西区', '南区', '北区', '中心区'],			//区域
	custType:['全部', 'A类', 'B类', 'C类'],							//用户类型
	
	element : function(tagId) {
		return document.getElementById(tagId);
	},

	checkboxHtml:function(label, id, name, checked){
		if (checked) {
			return '<input type="checkbox" id="'+id+'" name="'+name+'" checked="checked" value="'+label+'" /><label for="'+id+'">'+label+'</label>';
		} else {
			return '<input type="checkbox" id="'+id+'" name="'+name+'" value="'+label+'" /><label for="'+id+'">'+label+'</label>';		
		}
	}	
};

/**
 * 全局对象promotion
 * @type
 * 属性:xml
 * 方法:
 * select(xpath)
 * value(xpath)
 * load(promotionId)
 */

var promotion = {

	xml:null,
	
	id: 0,
	title: '',
	createdBy:'',
	createdOn:'',
	startDate:'',
	endDate:'',
	desc:'',
	publishedBy:'',
	publishedOn:'',
	cust:{areas:['全部'], types:['全部'], files:[]},
	attachment:[],
	question:[],
	result:new Hash(),
	resultCount:0,
	
	node:function(xpath) {
			if (this.xml==null) return null;
			var node=this.xml.documentElement.selectSingleNode(xpath);
			return node;
		},
	
	nodes:function(xpath) {
			if (this.xml==null) return null;
			var nodes=this.xml.documentElement.selectNodes(xpath);
			return nodes;			
		},
	
	text:function(xpath) {
			if (this.xml==null) return null;
			var nodeText=this.xml.documentElement.selectSingleNode(xpath).text;
			return nodeText;	
		},

	parseXml:function() {
			this.id=this.node('//promotion').getAttribute('id');
			this.title=(n=this.node('title')) ? n.text: '';
			this.createdBy=(n=this.node('createdBy')) ? n.text: '';
			this.createdOn=(n=this.node('createdOn')) ? n.text: '未知日期';
			this.publishedBy=(n=this.node('publishedBy')) ? n.text: '';
			this.publishedOn=(n=this.node('publishedOn')) ? n.text: '未知日期';
			this.desc=(n=this.node('desc')) ? n.text: '';
			this.startDate=(n=this.node('startDate')) ? n.text: '未知日期';
			this.endDate=(n=this.node('endDate')) ? n.text: '未知日期';
			
			//附件
			this.attachment=[];
			var n=this.nodes('attachment/file');
			for (var i=0; i<n.length; i++) this.attachment[i]=n[i].text;
			
			
			//目标客户
			this.cust.areas=['全部'];
			var n=this.nodes('cust/area');
			for (var i=0; i<n.length; i++) this.cust.areas[i]=n[i].text;
			
			this.cust.types=['全部'];
			var n=this.nodes('cust/type');
			for (var i=0; i<n.length; i++) this.cust.types[i]=n[i].text;

			this.cust.files=[];
			var n=this.nodes('cust/file');
			for (var i=0; i<n.length; i++) this.cust.files[i]=n[i].text;
			
			//调查问卷
			this.question=[];
			var n=this.nodes('questionnaire/question');
			for (var i=0; i<n.length; i++) {
				var q=new Object;
				q.title=n[i].firstChild.text;
				q.answers=[];
				var children=n[i].childNodes;
				for (var j=1; j<children.length; j++){
					q.answers[j-1]=children[j].text;
				};
				this.question[i]=q;
			};
			
/*			// 反馈记录
		this.result = new Hash();
		var resultNodes = this.nodes('result');
		this.resultCount = resultNodes.length;
		for (var i = 0; i < resultNodes.length; i++) {
			var r = new Object();
			r.custId = resultNodes[i].getAttribute('custId');
			var childNodes = resultNodes[i];

			r.custName = n
			r.userName
			r.userFullName
			r.date
			r.answer = new Hash();
			r.set(q, a)

			this.result.set(r.custId, r);
		}
*/		
	},
	
	setXml:function(o) {
		this.xml=o;
		this.parseXml();
	},
	
	load:function(promotionId) {
			var request=new XMLHttpRequest();
			request.open('GET', '/promotion/'+promotionId+'.xml', false);
			request.send();
			this.xml=request.responseXML;
			this.parseXml();
		}
};

var promotionUI = {
	
	//-----------------------填充界面-------------------
	fillBase : function() {
		ccms.element('promotionTitle').innerHTML=promotion.title;
		ccms.element('promotionId').innerHTML=promotion.id;
		ccms.element('promotionAuthor').innerHTML=promotion.createdBy+'于'+promotion.createdOn+'创建';
		ccms.element('promotionContent').innerText=promotion.desc;
		ccms.element('promotionDuration').innerHTML=promotion.startDate+'——'+promotion.endDate;
		//填充表单
		var form=ccms.element('promotionForm');
		form.title.value=promotion.title;
		form.startDate.value=promotion.startDate;
		form.endDate.value=promotion.endDate;
		form.desc.value=promotion.desc;
	},
	
	//在“附件清单”中点击删除链接
	onDeleteAttachmentClick:function(fileName) {
			//一定要在这里转码(utf-8)，不能让xmlHttpRequest自己转
			var f=encodeURIComponent(fileName);
			var url='/promotion/'+promotion.id+'/attachment/'+f;
			var request=new XMLHttpRequest();
			request.open('DELETE', url, false);
			request.send(null);
			promotion.setXml(request.responseXML);
			promotionUI.fillAttachment();
		},	
	
	//填充附件数据
	fillAttachment : function(){
		var nodes=promotion.nodes('attachment/file');
		if (nodes.length==0) {
			ccms.element('promotionAttachment').innerHTML='[没有附件]';
			ccms.element('promotionAttachmentFieldset').innerHTML='[没有附件]';
			return;
		};
		
		//填充显示区
		var html='';
		for (i=0;i<nodes.length;i++){
			html += '<a href="/store/upload/'+nodes[i].text+'">'+nodes[i].text+'</a>&nbsp;&nbsp;&nbsp;';
		};
		ccms.element('promotionAttachment').innerHTML=html;

		//填充编辑区
		html='<ul>';
		for (i=0;i<nodes.length;i++){
			html += '<li>'
			html += nodes[i].text;
			html += '<a href="#" onclick="javascript:promotionUI.onDeleteAttachmentClick(\''+nodes[i].text+'\')">删除</a>';
			html += '</li>'
		};
		html+='</ul>';
		ccms.element('promotionAttachmentFieldset').innerHTML=html;

		},
	
	//在“附加客户清单”中点击删除链接
	onDeletePromotionCustFileClick:function(fileName) {
			//一定要在这里转码(utf-8)，不能让xmlHttpRequest自己转
			var f=encodeURIComponent(fileName);
			var url='/promotion/'+promotion.id+'/custFile/'+f;
			var request=new XMLHttpRequest();
			request.open('DELETE', url, false);
			request.send(null);
			//alert(request.responseText);
			//alert(request.responseXML);
			promotion.setXml(request.responseXML);
			promotionUI.fillCust();
		},
		
	
	//填充客户数据
	fillCust:function() {
		var cust=promotion.cust;
		
		//填充显示区
		if (cust.areas[0]=='全部' && cust.types[0]=='全部') {
			ccms.element('promotionCust').innerHTML='全部集团客户';
		} else {
			var html='';
			for (var i=0; i<cust.areas.length; i++) html +=cust.areas[i];
			html += '的';
			for (var i=0; i<cust.types.length; i++) html +=cust.types[i];
			html += '集团客户&nbsp;';
			
			for (var i=0; i<cust.files.length; i++) {
				html +='<a href="/store/promotion/'+promotion.id+'/'+cust.files[i]+'">'+cust.files[i]+'</a>&nbsp';
			};
	
			ccms.element('promotionCust').innerHTML=html;
		};
		
		//填充编辑区
		var formHtml='<legend>选择区域</legend>';
		for (var i = 0, len = ccms.areas.length; i < len; ++i) {
			formHtml=formHtml+ccms.checkboxHtml(ccms.areas[i], 'promotionArea'+i, 'area', cust.areas.contains(ccms.areas[i]));
		};
		ccms.element('promotionCustAreaFieldset').innerHTML=formHtml;
	
		formHtml='<legend>选择类型</legend>';
		for (var i = 0, len = ccms.custType.length; i < len; ++i) {
			formHtml=formHtml+ccms.checkboxHtml(ccms.custType[i], 'promotionCustType'+i, 'custType', cust.types.contains(ccms.custType[i]));
		};
		ccms.element('promotionCustTypeFieldset').innerHTML=formHtml;	
	
		formHtml='<legend>附加客户清单</legend>';
		for (var i = 0, len = cust.files.length; i < len; ++i) {
			formHtml=formHtml+cust.files[i];
			formHtml=formHtml+'<a href="#" onclick="javascript:promotionUI.onDeletePromotionCustFileClick(\''+cust.files[i]+'\')">删除</a>';
			formHtml=formHtml+'<br />';
		};
		ccms.element('promotionCustFileFieldset').innerHTML=formHtml;
		
		
		$('promotionCustForm').action='/promotion/'+promotion.id+'/cust/';
		$('promotionCustFileForm').action='/promotion/'+promotion.id+'/custFile/';
		$('promotionAttachmentForm').action='/promotion/'+promotion.id+'/attachment/';
		$('questionnaireForm').action='/promotion/'+promotion.id+'/questionnaire/';
		
	},
	
	//填充调查问卷
	fillQuestionnaire: function() {
		var q=promotion.question;
		//填充显示区
		var html='';
		for (var i=0;i<q.length; i++){
			html += '<fieldset class="qFieldset">';
			html += '<legend>'+q[i].title+'</legend><ul>';
			for (var j=0;j<q[i].answers.length; j++){
				html += '<li>'+q[i].answers[j]+'</li>'
			};
			html += '</ul></fieldset>';
		};
		ccms.element('questionnaire').innerHTML=html;
		
		//填充编辑区
		var text='';
		for (var i=0;i<q.length; i++){
			text += q[i].title+'\r\n';
			for (var j=0; j<q[i].answers.length; j++){
				text +=q[i].answers[j]+'\r\n';
			};
			text +='\r\n';
		}
		if (text.length>4) text=text.substring(0,text.length-4);	//去掉最后两个回车
		ccms.element('questionnaireText').innerText=text;
		
		//活动反馈
		var sb=new StringBuffer();
		for (var i=0; i<q.length; i++) {
			sb.append('<fieldset>');
			sb.append('<legend>');
			sb.append(q[i].title);
			sb.append('</legend>');
			for (var j=0; j<q[i].answers.length; j++){
				sb.append('<input type="radio" name="q'+i+'" value="');
				sb.append(q[i].answers[j]);
				sb.append('" />');
				sb.append(q[i].answers[j]);
			}
			sb.append('</fieldset>');
		};
		$('promotionResultQuestionnaire').innerHTML=sb.toString();
		
	},
	
	show: function() {
		if (promotion.xml==null) {
			alert('未选择活动，请点击左边导航栏中的活动');
			return;
		}
		ccms.element('promotion').style.display='block';
		this.fillBase();
		this.fillAttachment();
		this.fillCust();
		this.fillQuestionnaire();
		this.showResult(1,100);
	},
	
	//填充反馈记录
	showResult:function(pageNum, count) {
		
		var sb=new StringBuffer();
		sb.append('<table border="1" cellpadding="1" width="100%">');
		sb.append('<tr class="navBox"><td>反馈</td><td>客户</td><td>问卷</td><td>操作</td></tr>');
		
		//计算分页的记录范围
		var startNum=(pageNum-1)*count;
		var endNum=pageNum*count-1;
		
		
		var resultNodes = promotion.nodes('result');
		promotion.resultCount = resultNodes.length;
		//分页的记录范围不能超过记录总数
		if (endNum>=resultNodes.length) endNum=resultNodes.length-1;
		for (var i = startNum; i <= endNum; i++) {
			var custId=resultNodes[i].getAttribute('custId');
			var childNodes=resultNodes[i].childNodes;
			var td1='';
			var td2='';
			var td3='';
			var td4='';
			for (var j=0; j<childNodes.length; j++) {
				var text=childNodes[j].text;
				switch (childNodes[j].nodeName){
					case 'date':
						td1=text;
						break;
					case 'reporter':
						td1+='<br />'+text;
						break;
					case 'custName':
						td2='<a href="/cust/'+custId+'">'+text+'</a>';
						break;
					case 'answer':
						var q=childNodes[j].getAttribute('title');
						td3+='<span style="display:block">'+q+':'+text+'</span>';
						break;
				}
			}
			
			
			sb.append('<tr>');
			sb.append('<td>');
			sb.append(td1);
			sb.append('</td>');

			sb.append('<td>');
			sb.append(td2);
			sb.append('</td>');
			
			sb.append('<td>');
			sb.append(td3);
			sb.append('</td>');
			sb.append('<td>');
			sb.append('</td>');
			sb.append('</tr>');
		};
		
		sb.append('</table>');
		//TODO 页码标签
		$('promotionResult').innerHTML=sb.toString();
		$('promotionResult').style.display='block';
	},
	
	
	//用户点击"编辑活动"链接
	onEditPromotionLinkClick : function(){
		//填充所有input框
		var form=ccms.element('promotionForm');
		form.title.value=promotion.title;
		form.startDate.value=promotion.startDate;
		form.endDate.value=promotion.endDate;
		form.desc.value=promotion.desc;
		//目标url为修改
		form.action='/promotion/'+promotion.id;
		//TODO 展开编辑区
		Effect.SlideDown('promotionBox');
		
	},
	
	//用户点击“新建活动”链接
	onNewPromotionLinkClick : function(){
		//清空所有input框
		var form=ccms.element('promotionForm');
		form.title.value='';
		form.startDate.value='';
		form.endDate.value='';
		form.desc.value='';
		//目标url为修改
		form.action='/promotion/';
		//$('promotionBox').style.display="block";
		//打开对话框
		Modalbox.show($('promotionBox'), {title: '新建活动', width: 600});
	},
	
	
	//用户提交“活动”
	onPromotionSubmitButtonClick: function(){
		
		var params=$('promotionForm').serialize();
		
		var request=new XMLHttpRequest();
		request.open('POST', $('promotionForm').action, false);
		request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		request.setRequestHeader('Content-length', params.length);
		request.send(params);
		
		promotion.setXml(request.responseXML);
		promotionUI.show();
		
		//关闭对话框
		if ($('promotionForm').action=='/promotion/') Modalbox.hide();
		else Effect.SlideUp('promotionBox');
		
	},
	
	//用户取消“新建活动”
	onPromotionCancelButtonClick: function() {
		if ($('promotionForm').action=='/promotion/') {
			Modalbox.hide();
			$('promotionBox').style.display="none";
		}
		else Effect.SlideUp('promotionBox');
	},
	
	onPromotionCustLinkClick:function() {
		Effect.SlideDown('promotionCustBox');
	},
	
	//用户提交目标客户---区域与类型
	onPromotionCustSubmitClick:function() {
		var params=$('promotionCustForm').serialize();
		
		var request=new XMLHttpRequest();
		request.open('POST', '/promotion/'+promotion.id+'/cust/', false);
		request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		request.setRequestHeader('Content-length', params.length);
		request.send(params);
		
		promotion.setXml(request.responseXML);
		promotionUI.fillCust();
		Effect.SlideUp('promotionCustBox');
	},
	
	//用户取消目标客户---区域与类型
	onPromotionCustCancelClick:function() {
		$('promotionCustForm').reset;
		Effect.SlideUp('promotionCustBox');
	},
	
	//用户提交目标客户---文件
	onPromotionCustFileFormSubmit:function() {
		$('promotionCustFileForm').target = 'upload_target';
		//TODO 监视文件传输结果，刷新客户信息区
		Effect.SlideUp('promotionCustBox');
	},
	
	//用户取消目标客户---区域与类型
	onPromotionCustFileCancelClick:function() {
		$('promotionCustFileForm').reset;
		Effect.SlideUp('promotionCustBox');		
	},
	
	//提交附件
	onPromotionAttachmentFormSubmit:function() {
		$('promotionAttachmentForm').target = 'upload_target';
		Effect.SlideUp('promotionAttachmentFormDiv');
		promotion.load(promotion.id);
		promotionUI.show();
	},
	
	//取消附件编辑
	onPromotionAttachmentCancelClick:function() {
		Effect.SlideUp('promotionAttachmentFormDiv');	
	},
	
	//提交调查问卷
	onQuestionnaireSubmitButtonClick:function() {
		var params=$('questionnaireForm').serialize();
		
		var request=new XMLHttpRequest();
		request.open('POST', $('questionnaireForm').action, false);
		request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		request.setRequestHeader('Content-length', params.length);
		request.send(params);
		
		promotion.setXml(request.responseXML);
		//Effect.SlideUp('questionnaireBox');
		promotionUI.fillQuestionnaire();
		Modalbox.hide();
	},
	
	//用户点击"提交客户反馈"
	onNewResultLinkClick:function(){
		//Modalbox.show()('<div>提交客户反馈<form></form></div>',{title:'提交客户反馈', width:500});
		Modalbox.show($('resultBox'), {title: '提交客户反馈', width: 600});
	},

	onAttachmentLinkClick:function() {
		Effect.SlideDown('promotionAttachmentFormDiv');
	},
	
	onPromotionResultSubmitButtonCilck:function(){
		var params=$('promotionResultForm').serialize();
		
		var request=new XMLHttpRequest();
		request.open('POST', $('promotionResultForm').action, false);
		request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		request.setRequestHeader('Content-length', params.length);
		request.send(params);
		
		promotion.setXml(request.responseXML);
		Effect.SlideUp('resultBox');
		promotionUI.showResult(1,50);
		
		//promotionUI.fillQuestionnaire();
	},
	
	onEditQuestionnaireLinkClick:function(){
		Effect.SlideDown('questionnaireBox');
	},
	
	
	//---------------用户行为事件处理，用户点击、拖放等事件的处理-------------------------

	registerEvent: function(){
		//基本信息操作
		//TODO 想清楚删除逻辑，是不是需要？如果需要怎么做？
		$('newPromotionLink').attachEvent('onclick', this.onNewPromotionLinkClick);
		$('editPromotionLink').attachEvent('onclick', this.onEditPromotionLinkClick);
		$('promotionSubmitButton').attachEvent('onclick', this.onPromotionSubmitButtonClick);
		$('promotionCancelButton').attachEvent('onclick', this.onPromotionCancelButtonClick);
		
		//目标客户操作
		$('promotionCustLink').attachEvent('onclick', this.onPromotionCustLinkClick);
		$('promotionCustFileForm').attachEvent('onsubmit', this.onPromotionCustFileFormSubmit)
		$('promotionCustSubmitButton').attachEvent('onclick', this.onPromotionCustSubmitClick);
		$('promotionCustCancelButton').attachEvent('onclick', this.onPromotionCustCancelClick);
		//$('promotionCustFileSubmitButton').attachEvent('onclick', this.onPromotionCustFileSubmitClick);
		$('promotionCustFileCancelButton').attachEvent('onclick', this.onPromotionCustFileCancelClick);
		
		//附件
		$('attachmentLink').attachEvent('onclick', this.onAttachmentLinkClick);
		$('promotionAttachmentForm').attachEvent('onsubmit', this.onPromotionAttachmentFormSubmit);
		$('promotionAttachmentCancelButton').attachEvent('onclick', this.onPromotionAttachmentCancelClick);
		
		//调查问卷
		$('questionnaireSubmitButton').attachEvent('onclick', this.onQuestionnaireSubmitButtonClick);
		$('promotionResultSubmitButton').attachEvent=('onclick', this.onPromotionResultSubmitButtonCilck);
		$('editQuestionnaireLink').attachEvent=('onclick', this.onEditQuestionnaireLinkClick);
	}
};

var nav={
	common:{
		
	},
	
	sales:{
		cust:null,
		promotion:null,
		task:null
	},
	
	areaAdmin:{
		
	},

	admin:{
		promotion:null
	},
	
	//展示管理员导航区
	loadAdmin:function(){
		var request=new XMLHttpRequest();
		//所有活动清单
		request.open('GET', '/promotion/list', false);
		request.send();
		this.admin.promotion=request.responseXML;
		var nodes=this.admin.promotion.documentElement.selectNodes('promotion');
		//if (nodes.length>0) $()
		var sb=new StringBuffer();
		for (var i=0; i<nodes.length; i++){
			sb.append('<a style="display:block" href="#" onclick="javascript:nav.onPromotionLinkClick(');
			sb.append(nodes[i].getAttribute('id'));
			sb.append(')">');
			sb.append(nodes[i].text);
			sb.append('</a>');
		};
		$('allPromotionNav').innerHTML=sb.toString();
		//alert(request.responseText);
	},
	
	loadSales:function(userName){
		var request=new XMLHttpRequest();
		//所有活动清单
		request.open('GET', '/testCustList.xml', false);
		request.send();
		this.sales.cust=request.responseXML;
		var nodes=this.sales.cust.documentElement.selectNodes('cust');
		//填充显示区-绘制表格
		var sb=new StringBuffer();
		for (var i=0; i<nodes.length; i++){
			sb.append('<a style="display:inline-block; padding-right:8px" href="#" onclick="javascript:nav.onCustLinkClick(');
			sb.append(nodes[i].getAttribute('id'));
			sb.append(')">');
			sb.append(nodes[i].text);
			sb.append('</a>');			
			//sb.append('&nbsp;&nbsp;');
		};
		$('salesCustNav').innerHTML=sb.toString();
		//填充编辑区
		var sb=new StringBuffer();
		//客户经理(userName)的客户
		for (var i=0; i<nodes.length; i++){
			sb.append('<input type="radio" name="custId" value="');
			sb.append(nodes[i].getAttribute('id'));
			sb.append('" />');
			sb.append(nodes[i].text);
		};
		$('promotionResultCustFieldset').innerHTML=sb.toString();
		//调查问卷在promotionUI中填充
	},
	
	onPromotionLinkClick:function(promotionId){
		promotion.load(promotionId);
		promotionUI.show();
	}
	
};



promotionUI.registerEvent();

nav.loadSales('admin');
nav.loadAdmin();

























